package com.xwyzsn.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xwyzsn.food.entity.Comment;
import com.xwyzsn.food.mapper.CommentMapper;
import com.xwyzsn.food.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scorpios
 * @since 2024-03-13
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper mapper;
    public Object get(Map<String,?> payload) {
        if(payload.containsKey("userId")){
            Integer userId = Integer.parseInt(String.valueOf(payload.get("userId")));
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            return mapper.selectList(wrapper);
        } else if (payload.containsKey("restId")) {
            Integer rest_id = Integer.parseInt(String.valueOf(payload.get("restId")));
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.eq("rest_id",rest_id);
            return mapper.selectList(wrapper);
        }
        return null;
    }

    public Object deleteOne(Map<String,?> payload) {
        Integer id  = Integer.parseInt(String.valueOf(payload.get("id")));
        return mapper.deleteById(id);
    }

    public Object addOne(Map<String,?> payload) {
        Comment entity = new Comment();
        if(payload.containsKey("userId")){
            Integer userId = Integer.parseInt(String.valueOf(payload.get("userId")));
            entity.setUserId(userId);
        }  if (payload.containsKey("restId")) {
            Integer restId = Integer.parseInt(String.valueOf(payload.get("restId")));
            entity.setRestId(restId);
        } if (payload.containsKey("content")) {
            String content = String.valueOf(payload.get("content"));
            entity.setContent(content);
        }
        return mapper.insert(entity);
    }

    public Object statics() throws IOException {
        ClassPathResource resource = new ClassPathResource("static.json");
        File file = resource.getFile();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        StringBuilder content = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line);
        }
        return content.toString();
    }
}
